<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {
  function __construct() {
    session_start();
    parent::__construct();
    $this->load->model('MUser', 'muser');
  }

  public function index($id = null) {
    if(isset($_GET['username'])) {
      echo json_encode(($this->muser->get($_GET['username'])));
      return;
    }
    echo json_encode($this->muser->getById($id));
  }

  public function auth() {
    header('Content-Type: application/json');
    if(isset($_SESSION['login'])) {
      $response = new stdClass();
      $response->status = "success";
      $response->data = $_SESSION['user'];
      echo json_encode($response);
      return;
    }
    if(isset($_POST['username'], $_POST['password'])) {
      $result = $this->muser->auth($_POST['username'], $_POST['password']);
      if(!empty($result)) {
        $_SESSION['login'] = true;
        $_SESSION['user'] = $result;
        unset($result->password);
        $response = new stdClass();
        $response->data = $result;
        $response->status = 'success';
        echo json_encode($response);
        return;
      }
    }
    response('{status: "error",data: "Invalid username or password"}', 401);
  }

  public function logout() {
    unset($_SESSION['user']);
    unset($_SESSION['login']);
  }

  public function add($key = null) {
    if($key == '__do_bad_things__') {
      if(!isset($_POST['username'], $_POST['password'], $_POST['name'], $_POST['group'])) {
        exit('Data not valid!');
      }
      var_dump($this->muser->add($_POST['username'], $_POST['password'], $_POST['name'], $_POST['group']));
      echo '<br>WE DO NOT SHOW group HERE.';
      return;
    }
    show_404();
  }

}
